﻿using BusinessLayer.DatabaseEntities;
using BusinessLayer.VDataEntities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace BusinessLayer
{
    public class TicketBusiness
    {
        //根据用户的名字和状态查询用户的所有申请
        public static VTicketEntity[] GetTickets(long userID = 0, int applicationStatus = 0, int ticketid = -1)
        {
            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {
                var tickets = from ticket in entities.Ticket
                              where ticket.IsActive == true
                              join assigner in entities.Operator
                              on ticket.Assigner equals assigner.ID
                              into assigners
                              from btb in assigners.DefaultIfEmpty()
                              join user in entities.EndUser
                              on ticket.EndUserID equals user.ID
                              into userinfo
                              from usi in userinfo.DefaultIfEmpty()
                              where (userID == 0 ? (true) : (usi.ID == userID))
                                       && (usi.IsActive == true)
                                       && (applicationStatus == 0 ? (true) : (applicationStatus == 2 ? ticket.Status == 4 : (ticket.Status != 4)))//若未传入applicationStatus时，查询所有
                                       && (ticketid == -1 ? (true) : (ticket.ID == ticketid))
                              select new VTicketEntity()
                              {
                                  TicketID = ticket.ID,
                                  ApplicationID = ticket.ApplicationID,
                                  User = new VEndUser
                                  {
                                      ID = ticket.EndUserID,
                                      ClientID = usi.ClientID,
                                  },
                                  Status = ticket.Status,
                                  SubmitDate = ticket.SubmiteDate,
                                  AssignDate = ticket.AssignDate,
                                  AssignerInfo = new VOperator
                                  {
                                      ID = ticket.Assigner,
                                      Mobile = btb.Mobile,
                                      Telephone = btb.Telephone,
                                      Email = btb.Email,
                                      Name = btb.UserName,
                                  },
                                  IssueDescription = ticket.IssueDescription,
                                  IssueType = ticket.IssueType,
                                  ServiceRate = ticket.ServiceRate,
                                  CloseDate = ticket.CloseDate,
                                  ServiceComments = ticket.ServiceComments,
                                  Email = ticket.Email,
                                  Mobile = ticket.Mobile
                              };
                //TestInfo.WriteInfoToLog(tickets.ToArray());
                //------添加了降序排序
                return tickets.OrderByDescending(u => u.SubmitDate).ToArray();
            }
        }

        //查询某一申请的处理进度
        public static TicketOperationLog[] GetTicketOperationLog(long ticketID)
        {
            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {

                var ticketOperationLogs = from logs in entities.TicketOperationLog
                                          where logs.TicketID == ticketID
                                          select logs;
                return ticketOperationLogs.ToArray();
            }
        }

        //操作某一请求的状态
        public static int ModifyTicketStatus(VTicketStatus vs)
        {
            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {
                int result = 1;
                var ticket = (from t in entities.Ticket
                              where t.ID == vs.ticketID
                              select t).FirstOrDefault();
                if (ticket != null)
                {
                    //记录操作日志
                    result = AddOperationLog(vs.ticketID, vs.actorName, vs.ticketStatus);
                    if (result > 0)
                    {
                        //添加备注
                        ticket.Status = vs.ticketStatus;
                        AddComments(vs);
                        result = entities.SaveChanges();
                    }
                    else
                    {
                        result = -1;
                    }
                }
                return result;
            }


        }

        //记录操作日志
        public static int AddOperationLog(long ticketID, string actorName, int operation)
        {
            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {
                TicketOperationLog operationLog = new TicketOperationLog();
                operationLog.ActorName = actorName;
                operationLog.Operation = operation;
                operationLog.TicketID = ticketID;
                operationLog.OperationTime = System.DateTime.Now;

                entities.TicketOperationLog.Add(operationLog);
                //添加详细描述
                return entities.SaveChanges();
            }

        }

        #region 工程师可查询自己负责项目的请求
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="status"></param>
        /// <param name="project"></param>
        /// <param name="operatorId"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="roleId"></param>
        /// <param name="applicationID"></param>
        /// <returns></returns>
        public static List<VTicketsRequestInfo> FindTickets(int[] status, int project, int operatorId, DateTime startDate, DateTime endDate, int currentPage, int pageSize, int roleId, long[] applicationID, string type = null, int IsFromWeChat = 0,int priority = 0,int issueType = 0)
        {

            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {
                try
                {
                    var tickets = (from iticket in entities.Ticket
                                   join enduser in entities.EndUser on iticket.EndUserID equals enduser.ID into enduserAnditicket
                                   from gc1enduser in enduserAnditicket.DefaultIfEmpty()
                                   join client in entities.Client on gc1enduser.ClientID equals client.ID into clientAnditicket
                                   from gc1client in clientAnditicket.DefaultIfEmpty()
                                   where (roleId == 1 ? (true) : iticket.Assigner != null && applicationID.Contains(iticket.ApplicationID))
                                      && (operatorId <= 0 ? (true) : (iticket.Assigner == operatorId))
                                      && (status.Contains(-1) ? (true) : status.Contains(iticket.Status))
                                      && (project <= 0 ? (true) : (iticket.ApplicationID == project))
                                      && (iticket.SubmiteDate >= startDate)
                                      && (iticket.SubmiteDate <= endDate)
                                      && (IsFromWeChat == 0 ? (true) : (iticket.IsFromWeChat == IsFromWeChat))
                                      && (priority <= 0 ? (true) : (iticket.Priority == priority))
                                      && (issueType <= 0 ? (true) : (iticket.IssueType == priority))
                                   select new VTicketsRequestInfo
                                   {
                                       ApplicationID = iticket.ApplicationID,
                                       SubmitDate = iticket.SubmiteDate,
                                       AssignDate = iticket.AssignDate,
                                       AssignerInfo = new VOperator
                                       {
                                           ID = iticket.Assigner,
                                       },
                                       User = new VEndUser
                                       {
                                           Name = gc1enduser.UserName,
                                           ClientID = gc1client.ID,
                                       },
                                       IssueDescription = iticket.IssueDescription,
                                       IssueTypeDescription = iticket.IssueType1.IssueTypeDescription,
                                       TicketID = iticket.ID,
                                       Status = iticket.Status,
                                       ServiceRate = iticket.ServiceRate,
                                       Client = new VClient
                                       {
                                           ID = gc1client.ID,
                                           IsActive = gc1client.IsActive,
                                           Name = gc1client.ClientName,
                                           WechatID = gc1client.CropID,
                                       },
                                       ReportTicketNo = null,
                                       IsFromWeChat = iticket.IsFromWeChat,
                                       Mobile = iticket.Mobile,
                                       Email = iticket.Email
                                   });

                    int pageCount = tickets.Select(t => t.TicketID).Count();
                    //排序并分页
                    if (pageCount > 0)
                    {

                        tickets = tickets.OrderByDescending(u => u.SubmitDate).Skip((currentPage - 1) * pageSize).Take(pageSize);
                    }
                    return tickets.ToList();

                }
                catch (Exception e)
                {
                    Writelog("InnerException :" + e.InnerException+ "Message :" + e.Message+ "Source :" + e.Source+ "StackTrace :" + e.StackTrace+ "TargetSite :" + e.TargetSite+ "HelpLink :" + e.HelpLink);
                    throw e;
                }
            }
        }
        #endregion 结束查询


        #region 手写日志
        private static void Writelog(string log)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory;
            string fileName = DateTime.Now.ToString("yyyyMMdd") + ".log";
            var filePath = Path.Combine(path, fileName);
            using (FileStream fs=new FileStream (filePath,FileMode.OpenOrCreate))
            {
                fs.Position = fs.Length;
                var bytes = System.Text.Encoding.UTF8.GetBytes(log);
                fs.Write(bytes, 0, bytes.Length);
                fs.Flush();
            }
        }
        #endregion


        /// <summary>
        /// 工程师可查询自己负责项目的请求
        /// 获取总页数
        /// </summary>
        /// <param name="priority"></param>
        /// <param name="status"></param>
        /// <param name="project"></param>
        /// <param name="Date"></param>
        /// <returns></returns>
        public static int GetCount(int[] status, int project, DateTime startDate, DateTime endDate, int operatorId, int roleId, long[] applicationID, string type = null, int IsFromWeChat = 0,int priority = 0,int issueType = 0)
        {
            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {

                var tickets = (from iticket in entities.Ticket
                               join enduser in entities.EndUser on iticket.EndUserID equals enduser.ID into enduserAnditicket
                               from gc1enduser in enduserAnditicket.DefaultIfEmpty()
                               join client in entities.Client on gc1enduser.ClientID equals client.ID into clientAnditicket
                               from gc1client in clientAnditicket.DefaultIfEmpty()
                               where (roleId == 1 ? (true) : iticket.Assigner != null && applicationID.Contains(iticket.ApplicationID))
                                  && (operatorId <= 0 ? (true) : (iticket.Assigner == operatorId))
                                  && (status.Contains(-1) ? (true) : status.Contains(iticket.Status))
                                  && (project <= 0 ? (true) : (iticket.ApplicationID == project))
                                  && (iticket.SubmiteDate >= startDate)
                                  && (iticket.SubmiteDate <= endDate)
                                  && (IsFromWeChat == 0 ? (true) : (iticket.IsFromWeChat == IsFromWeChat))
                                  && (priority <= 0 ? (true) : (iticket.Priority == priority))
                                  && (issueType <= 0 ? (true) : (iticket.IssueType == priority))
                               select new VTicketsRequestInfo
                               {
                                   ApplicationID = iticket.ApplicationID,
                                   SubmitDate = iticket.SubmiteDate,
                                   AssignDate = iticket.AssignDate,
                                   AssignerInfo = new VOperator
                                   {
                                       ID = iticket.Assigner,
                                   },
                                   User = new VEndUser
                                   {
                                       Name = gc1enduser.UserName,
                                       ClientID = gc1client.ID,
                                   },
                                   IssueDescription = iticket.IssueDescription,
                                   IssueTypeDescription = iticket.IssueType1.IssueTypeDescription,
                                   TicketID = iticket.ID,
                                   Status = iticket.Status,
                                   ServiceRate = iticket.ServiceRate,
                                   Client = new VClient
                                   {
                                       ID = gc1client.ID,
                                       IsActive = gc1client.IsActive,
                                       Name = gc1client.ClientName,
                                       WechatID = gc1client.CropID,
                                   },
                                   ReportTicketNo = null,
                                   IsFromWeChat = iticket.IsFromWeChat,
                                   Mobile = iticket.Mobile,
                                   Email = iticket.Email
                               });

                int pageCount = tickets.Select(t => t.TicketID).Count();

                return pageCount;
            }

        }

        /// <summary>
        /// 获取tickets的详细信息
        /// </summary>
        /// <param name="ticketId"></param>
        /// <returns></returns>
        public static VTicketsRequestInfo GetTicketDetails(int ticketId, int IsFromWechat = 1)
        {

            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {

                if (IsFromWechat == 1)
                {
                    var tickets = (from iticket in entities.Ticket
                                   join enduser in entities.EndUser on iticket.EndUserID equals enduser.ID into enduserAndticket
                                   from gc2enduser in enduserAndticket.DefaultIfEmpty()

                                   where iticket.ID == ticketId
                                   select new VTicketsRequestInfo
                                   {
                                       AssignerInfo = new VOperator
                                       {
                                           ID = iticket.Assigner,
                                       },
                                       //AssignerName = gc1operator.UserName,
                                       ApplicationID = iticket.ApplicationID,
                                       User = new VEndUser
                                       {
                                           ID = gc2enduser.ID,
                                           Name = gc2enduser.UserName,
                                           ClientID = gc2enduser.ClientID
                                       },
                                       TicketID = iticket.ID,
                                       IssueDescription = iticket.IssueDescription,
                                       //IssueType = iticket.IssueType,
                                       IssueTypeDescription = iticket.IssueType1.IssueTypeDescription,
                                       Status = iticket.Status,
                                       Client = new VClient()
                                       {
                                           ID = iticket.Application.Client.ID,
                                           Name = iticket.Application.Client.ClientName,
                                           WechatID = iticket.Application.Client.CropID,
                                           IsActive = iticket.Application.Client.IsActive
                                       },
                                       ReportTicketNo = null,
                                       ServiceComments = iticket.ServiceComments,
                                       IsFromWeChat = iticket.IsFromWeChat,
                                       Priority = iticket.Priority,
                                       Email = iticket.Email,
                                       Mobile = iticket.Mobile,
                                       SubmitDate = iticket.SubmiteDate,
                                       ResolveDate = iticket.ResolveDate,
                                       CloseDate = iticket.CloseDate,
                                   }).FirstOrDefault();
                    //tickets.InputFieldData = ticketData.ToArray();
                    return tickets;

                }
                else
                {
                    var tickets = (from ireport in entities.Report
                                   join client in entities.Client on (ireport.CustomerID) equals client.ID into clientAndireport
                                   from gc1client in clientAndireport.DefaultIfEmpty()
                                   where ireport.ID == ticketId
                                   select new VTicketsRequestInfo
                                   {
                                       AssignerInfo = new VOperator
                                       {
                                           ID = (long)(null == ireport.SolvedUserID ? (ireport.FirstAssignedUserID) : (ireport.SolvedUserID)),
                                       },
                                       //AssignerName = gc1operator.UserName,
                                       ApplicationID = ireport.ProjectID,
                                       User = new VEndUser
                                       {
                                           Name = ireport.OpenBy,
                                           ClientID = gc1client.ID,
                                       },
                                       Comments = null,
                                       //EndUserID = ireport.EndUserID,
                                       TicketID = ireport.ID,
                                       IssueDescription = ireport.Description,
                                       //IssueType = ireport.IssueType,
                                       IssueTypeDescription = ireport.RequestCI,
                                       Status = ireport.Status,
                                       Client = new VClient()
                                       {
                                           ID = gc1client.ID,
                                           Name = gc1client.ClientName,
                                           WechatID = gc1client.CropID,
                                           IsActive = gc1client.IsActive
                                       },
                                       ReportTicketNo = ireport.TicketNo,
                                       IsFromWeChat = ireport.IsFromWeChat,
                                   }).FirstOrDefault();
                    return tickets;

                }
            }
        }

        /// <summary>
        /// 安排人员，修改状态
        /// </summary>
        /// <param name="assigner"></param>
        /// <param name="status"></param>
        /// <param name="ticketId"></param>
        public static void AssignAndModifyStatus(int IsFromWeChat, long ticketId, int assigner = 0, int status = -1)
        {
            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {
                var ticket = (from iticket in entities.Ticket
                              where (iticket.ID == ticketId) && (iticket.IsFromWeChat == IsFromWeChat)
                              select iticket).FirstOrDefault();
                if (assigner != 0)
                {
                    ticket.Assigner = assigner;
                    ticket.AssignDate = DateTime.Now;
                }
                //修改状态并修改解决和关闭时间
                if (status != -1)
                {
                    ticket.Status = status;
                    if (status == 3)
                    {
                        ticket.ResolveDate = DateTime.Now;
                    }
                    if (status == 4)
                    {
                        ticket.CloseDate = DateTime.Now;
                    }
                }
                entities.SaveChanges();
            }
        }

        /// <summary>
        /// 获取operator的信息
        /// </summary>
        /// <param name="operatorId"></param>
        /// <returns></returns>
        public static List<VOperator> GetOperatorInfo(long operatorId = 0)
        {
            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {
                var operatorInfo = from item in entities.Operator
                                   where ((operatorId == 0) ? (true) : (item.ID == operatorId)) && (item.IsActive == true)
                                   select new VOperator
                                   {
                                       ID = item.ID,
                                       Mobile = item.Mobile,
                                       Name = item.UserName,
                                       Telephone = item.Telephone,
                                       Email = item.Email,
                                       PassWord = item.Password,
                                       IsActive = item.IsActive
                                   };

                return operatorInfo.ToList();
            };
        }

        /// <summary>
        /// pc端根据条件查找ENDUSER信息
        /// </summary>
        /// <param name="EndUserId"></param>
        /// <returns></returns>
        public static List<VEndUser> GetEndUserInfo(long EndUserId = 0)
        {
            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {
                var endUserInfo = from info in entities.EndUser
                                  where (EndUserId == 0 ? (true) : info.ID == EndUserId) && info.IsActive == true
                                  select new VEndUser
                                  {
                                      ID = info.ID,
                                      Name = info.UserName,
                                      ClientID = info.ClientID,
                                      Client = new VClient()
                                      {
                                          ID = info.ClientID,
                                          Name = info.Client.ClientName,
                                          WechatID = info.Client.CropID
                                      },
                                      openid = info.openid
                                  };
                return endUserInfo.ToList();
            };
        }

        //添加备注信息
        public static int AddComments(VTicketStatus vs)
        {
            using (CustomerServiceCenterEntities csc = new CustomerServiceCenterEntities())
            {
                TicketCommentsHistory tch = new TicketCommentsHistory();
                tch.TicketID = vs.ticketID;
                tch.Comments = vs.Comments;
                tch.ActorName = vs.actorName;
                tch.SubmitDateTime = System.DateTime.Now;
                csc.TicketCommentsHistory.Add(tch);
                return csc.SaveChanges();
            }
        }

        /// <summary>
        /// 获得对话历史记录
        /// </summary>
        /// <returns></returns>
        public static List<VTicketCommentsHistory> GetCommentsHistory(long TicketID)
        {

            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {
                var commnetsHistory = entities.TicketCommentsHistory.Where(p => p.TicketID == TicketID).OrderBy(p => p.ID);
                List<VTicketCommentsHistory> commentsList = new List<VTicketCommentsHistory>();
                foreach (var item in commnetsHistory)
                {
                    VTicketCommentsHistory ticketsCommentsHistory = new VTicketCommentsHistory();
                    ticketsCommentsHistory.ID = item.ID;
                    ticketsCommentsHistory.ActorName = item.ActorName;
                    ticketsCommentsHistory.Comments = item.Comments;
                    ticketsCommentsHistory.SubmitDateTime = item.SubmitDateTime;
                    ticketsCommentsHistory.TicketID = item.TicketID;
                    commentsList.Add(ticketsCommentsHistory);
                }
                return commentsList;
            };
        }

        /// <summary>
        /// 获取图片的信息
        /// </summary>
        /// <returns></returns>
        public static List<VImage> GetImage(long TicketID)
        {
            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {
                var image = from info in entities.Image
                            where info.TicketID == TicketID && info.IsActive == true
                            select new VImage
                            {
                                ID = info.ID,
                                Path = info.Path,
                                TicketID = info.TicketID,
                                UploadDate = info.UploadDate
                            };

                return image.ToList();
            }
        }

        /// <summary>
        /// 获取操作员的tickets的信息
        /// </summary>
        /// <param name="operatorID"></param>
        /// <returns></returns>
        public static List<VTicketsRequestInfo> GetTicketsInfoByOperator(long roleId, long[] applicationID)
        {
            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {
                var tickets = from iticket in entities.Ticket
                              join enduser in entities.EndUser on iticket.EndUserID equals enduser.ID into enduserAnditicket
                              from gc1enduser in enduserAnditicket.DefaultIfEmpty()
                              where (roleId == 1 ? (true) : applicationID.Contains(iticket.ApplicationID))
                              select new VTicketsRequestInfo
                              {
                                  ApplicationID = iticket.ApplicationID,
                                  SubmitDate = iticket.SubmiteDate,
                                  AssignDate = iticket.AssignDate,
                                  AssignerInfo = new VOperator
                                  {
                                      ID = iticket.Assigner,
                                  },
                                  User = new VEndUser
                                  {
                                      ID = gc1enduser.ID,
                                      Name = gc1enduser.UserName,
                                      ClientID = gc1enduser.ClientID,
                                  },
                                  IssueDescription = iticket.IssueDescription,
                                  IssueType = iticket.IssueType,
                                  TicketID = iticket.ID,
                                  Status = iticket.Status,

                              };

                return tickets.ToList();
            }

        }
        /// <summary>
        /// 批量导入Ticket报表
        /// </summary>
        /// <param name="report"></param>
        /// <returns></returns>
        public static long ImportTickets(Report report)
        {
            long ticketID = -1;
            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {
                Report reportTicket = new Report();
                reportTicket.ApplicationName = report.ApplicationName;
                reportTicket.AssignDate = report.AssignDate;
                reportTicket.AssignmentGroup = report.AssignmentGroup;
                reportTicket.CustomerID = report.CustomerID;
                reportTicket.Description = report.Description;
                reportTicket.FirstAssignedUserID = report.FirstAssignedUserID;
                reportTicket.FirstAssignedUserName = report.FirstAssignedUserName;
                reportTicket.Location = report.Location;
                reportTicket.Module = report.Module;
                reportTicket.OpenBy = report.OpenBy;
                reportTicket.OpenDate = report.OpenDate;
                reportTicket.Priority = report.Priority;
                reportTicket.ProjectID = report.ProjectID;
                reportTicket.RequestCI = report.RequestCI;
                reportTicket.SolvedDate = report.SolvedDate;
                reportTicket.SolvedUserID = report.SolvedUserID;
                reportTicket.SolvedUserName = report.SolvedUserName;
                reportTicket.Status = report.Status;
                reportTicket.TicketNo = report.TicketNo;
                reportTicket.Title = report.Title;
                reportTicket.Type = report.Type;
                reportTicket.IsFromWeChat = report.IsFromWeChat;
                entities.Report.Add(reportTicket);
                entities.SaveChanges();
                ticketID = reportTicket.ID;

            }
            return ticketID;
        }

        /// <summary>
        /// 用于验证Client和Application
        /// </summary>
        /// <param name="clientid"></param>
        /// <param name="applicationid"></param>
        /// <returns></returns>
        public static VApplication GetClientAndApplication(long clientid, long applicationid)
        {
            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {
                var app = from application in entities.Application
                          where application.ClientID == clientid
                          && application.ID == applicationid
                          select new VApplication()
                          {
                              ID = application.ID,
                              ClientID = application.ClientID,
                              Name = application.Name,
                              IsWeChatActive = application.IsWeChatActive,
                          };
                return app.FirstOrDefault();
            }
        }

        /// <summary>
        /// 修改tickets的内容
        /// </summary>
        /// <param name="TicketID"></param>
        /// <param name="Remark"></param>
        /// <param name="IssueTypeID"></param>
        /// <param name="ApplicationID"></param>
        public static void ModifyTicketsInfo(long TicketID, string Description, long IssueTypeID, string Type, int priority)
        {
            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {
                var tickets = (from info in entities.Ticket
                               where info.ID == TicketID
                               select info).FirstOrDefault();
                if (null != tickets)
                {
                    if (null != Description)
                    {
                        tickets.IssueDescription = Description;
                    }
                    if (IssueTypeID > 0)
                    {
                        tickets.IssueType = IssueTypeID;
                    }
                    if (priority > 0)
                    {
                        tickets.Priority = priority;
                    }
                }
                entities.SaveChanges();
            }
        }

        /// <summary>
        /// 根据条件查找tickets信息
        /// </summary>
        /// <param name="EndUserID"></param>
        /// <returns></returns>
        public static VTicketRequest GetTicketsBySome(long EndUserID)
        {
            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {
                var tickets = (from info in entities.Ticket
                               where info.EndUserID == EndUserID
                               select info).OrderByDescending(u => u.SubmiteDate).FirstOrDefault();
                VTicketRequest ticketsInfo = new VTicketRequest();
                if (tickets != null)
                    ticketsInfo = new VTicketRequest
                    {
                        ApplicationID = tickets.ApplicationID,
                        EndUserId = tickets.EndUserID,
                        ID = tickets.ID,
                        IsFromWeChat = tickets.IsFromWeChat,
                        IssueDescription = tickets.IssueDescription,
                        IssueType = tickets.IssueType,
                        Status = tickets.Status,
                    };
                return ticketsInfo;
            }
        }


        public static List<VTicketEntity> GetAllTickets()
        {
            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {
                var tickets = (from info in entities.Ticket
                               select new VTicketEntity
                               {
                                   TicketID = info.ID,
                                   ApplicationID = info.ApplicationID,
                                   User = new VEndUser { ID = info.EndUserID },
                                   Status = info.Status,
                                   SubmitDate = info.SubmiteDate,
                                   AssignDate = info.AssignDate,
                                   AssignerInfo = new VOperator
                                   {
                                       ID = info.Assigner,
                                   },
                                   ServiceRate = info.ServiceRate,
                                   CloseDate = info.CloseDate,
                                   ServiceComments = info.ServiceComments,
                                   ResolveDate = info.ResolveDate
                               });
                return tickets.ToList();
            }
        }


        public static List<VTicketInputField> GetTicketInputFieldBySome(long applicationId,long IssueTypeID=0)
        {
            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {
                var ticketInputField = from field in entities.TicketInputField
                                       where ((IssueTypeID ==0)?(true):(field.IssueTypeID == IssueTypeID)) && (field.ApplicationID == applicationId)
                                       select new VTicketInputField
                                       {
                                           Id = field.Id,
                                           DataType = field.DataType,
                                           Description = field.Description,
                                           IssueTypeID = field.IssueTypeID,
                                           Name = field.Name,
                                           SortSeq = field.SortSeq,
                                           IsMandary = field.IsMandary,
                                           EnglishName = field.EnglishName,
                                           ApplicationID = field.ApplicationID,
                                       };
                return ticketInputField.OrderBy(p => p.SortSeq).ToList();

            }
        }


        public static List<VInputFieldDataSource> GetInputDataSourceByFieldID(long TicketInputFieldID)
        {
            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {
                var dataSource = from data in entities.InputFieldDataSource
                                 where data.TicketInputFieldID == TicketInputFieldID
                                 select new VInputFieldDataSource
                                 {
                                     Description = data.Description,
                                     Id = data.Id,
                                     TicketInputFieldID = data.TicketInputFieldID,
                                     value = data.value

                                 };
                return dataSource.ToList();
            }
        }


        public static void CancelTicketByID(long TicketID)
        {
            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {
                var ticket = entities.Ticket.Where(p => p.ID == TicketID).FirstOrDefault();
                ticket.IsActive = false;
                entities.SaveChanges();
            }
        }




        /// <summary>
        ///  GetFieldDataBySome
        /// </summary>
        /// <param name="TicketID">TicketID</param>
        /// <param name="TicketInputFieldID">TicketInputFieldID</param>
        /// <returns></returns>
        public static List<VTicketInputFieldData> GetFieldDataBySome(long TicketID = 0, long TicketInputFieldID = 0)
        {
            using (CustomerServiceCenterEntities entities = new CustomerServiceCenterEntities())
            {
                var data = from info in entities.TicketInputFieldData
                           where (TicketID == 0 ? true : info.TicketID == TicketID) && (TicketInputFieldID == 0 ? true : info.TicketInputFieldID == TicketInputFieldID)
                           select new VTicketInputFieldData
                           {
                               ID = info.ID,
                               TicketID = info.TicketID,
                               TicketInputFieldID = info.TicketInputFieldID,
                               Value = info.Value
                           };

                return data.ToList();
            }
        }

    }
}
